package cn.tedu.micro.demo.client;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * 测试消费确认
 */
@Slf4j
public class RabbitmqConsumeConfirm {
    //自动确认
    @Test
    public void autoAck() throws IOException, InterruptedException {
        //1.获取连接
        Channel channel = RabbitChannelManager.newChannel();
        //2.监听消费queue01
        channel.basicConsume(
                "queue01",
                true,//收到消息同时 就反馈确认
                (consumerTag,message)->{
                    //消费入口 deliver#handle
                    log.info("msg:"+new String(message.getBody()));
                },
                consumerTag->{
                    //消费趋势小 cancel#handle
                }
        );
        //3.添加一个阻塞 查看消费打印日志
        Thread.sleep(10000000);
    }
    //手动确认
    @Test
    public void manualAck() throws IOException, InterruptedException {
        //1.获取连接
        Channel channel = RabbitChannelManager.newChannel();
        //2.监听消费queue01
        channel.basicConsume(
                "biz_q",
                false,//不在自动确认,需要消费代码手动调用api确认
                (consumerTag,message)->{
                    //消费入口 deliver#handle
                    log.info("msg:"+new String(message.getBody()));
                    //根据消费结果确认
                    //如果消费成功
                    //channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                    //如果消费失败
                    channel.basicNack(message.getEnvelope().getDeliveryTag(),false,false);
                },
                consumerTag->{
                    //消费趋势小 cancel#handle
                }
        );
        //3.添加一个阻塞 查看消费打印日志
        Thread.sleep(10000000);
    }
}
